import { CopyOutlined } from '@ant-design/icons';
import { App, Button, Input, Modal, Popover, Switch } from 'antd';
import React, { ReactElement, useMemo, useState } from 'react';
import ReactDOMServer from 'react-dom/server';

import IframeImage from './image/tiangong_iframe.png';
import LinkImage from './image/tiangong_link.png';
import ScriptImage from './image/tiangong_script.png';

interface UsageMethodModalProps {
  open: boolean;
  onCancel: () => void;
  shareLink?: string;
}

type UsageType = 'link' | 'iframe' | 'script';

const OptionItem: React.FC<{
  label: string;
  checked: boolean;
  onChange: (checked: boolean) => void;
}> = ({ label, checked, onChange }) => (
  <div className="flex w-48 items-center justify-between rounded-lg border border-[#e8ebf0] bg-[#f4f6f8] p-3">
    <label className="text-sm">{label}</label>
    <Switch checked={checked} onChange={onChange} />
  </div>
);

const IconOptionItem: React.FC<{
  label: string;
  icon: string;
  onIconChange: (newIcon: string) => void;
  iconList: ReactElement[];
  onFileUpload: (file: File) => void;
}> = ({ label, icon, onIconChange, iconList, onFileUpload }) => {
  const [popoverVisible, setPopoverVisible] = useState(false);

  const handleIconSelect = (newIcon: ReactElement) => {
    const iconDataUrl = getIconDataUrl(newIcon);
    onIconChange(iconDataUrl);
    setPopoverVisible(false);
  };

  const handleFileInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      onFileUpload(file);
      setPopoverVisible(false);
    }
  };

  const iconPicker = (
    <div style={{ maxWidth: 200 }}>
      {/* <div className="grid grid-cols-5 gap-4 mb-4">
        {iconList.map((ico, index) => (
          <div key={index} className="cursor-pointer" onClick={() => handleIconSelect(ico)}>
            {ico}
          </div>
        ))}
      </div> */}
      {/* <div className="border-t pt-2"> */}
      <label className="hover:text-blue-700 cursor-pointer text-blue-500">
        上传自定义图标
        <input type="file" accept="image/*" onChange={handleFileInputChange} className="hidden" />
      </label>
      {/* </div> */}
    </div>
  );

  return (
    <div className="flex w-48 items-center justify-between rounded-lg border border-[#e8ebf0] bg-[#f4f6f8] p-3">
      <label className="text-sm">{label}</label>
      <Popover
        content={iconPicker}
        trigger="click"
        open={popoverVisible}
        onOpenChange={setPopoverVisible}
      >
        <div className="cursor-pointer">
          <img src={icon} alt={label} className="h-6 w-6" />
        </div>
      </Popover>
    </div>
  );
};

const getIconDataUrl = (iconComponent: ReactElement): string => {
  const markup = ReactDOMServer.renderToStaticMarkup(iconComponent);
  const svgRegex = /<svg.*?>.*?<\/svg>/s;
  const match = markup.match(svgRegex);

  if (!match) {
    return '';
  }
  const svgString = match[0];
  const cleanedSvgString = svgString.replace(/\s{2,}/g, ' ').replace(/\n/g, '');
  const base64String = btoa(cleanedSvgString);
  return `data:image/svg+xml;base64,${base64String}`;
};

const UsageMethodModal: React.FC<UsageMethodModalProps> = ({ open, onCancel, shareLink = '' }) => {
  const { message } = App.useApp();
  const [activeUsage, setActiveUsage] = useState<UsageType>('link');

  const [showHistory, setShowHistory] = useState(true);
  const [isDraggable, setIsDraggable] = useState(true);
  const [defaultOpen, setDefaultOpen] = useState(true);

  const commonIconProps = { fill: '#5084fd', className: 'text-lg' };

  // 默认的 base64 图标
  const defaultOpenIconBase64 =
    '';
  const defaultCloseIconBase64 =
    '';

  const [openIcon, setOpenIcon] = useState(defaultOpenIconBase64);
  const [closeIcon, setCloseIcon] = useState(defaultCloseIconBase64);

  // 将图片转换为 base64
  const convertImageToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  };

  // 处理文件上传
  const handleFileUpload = async (file: File, setIcon: (icon: string) => void) => {
    try {
      const base64 = await convertImageToBase64(file);
      setIcon(base64);
      message.success('图标上传成功');
    } catch (error) {
      message.error('图标上传失败');
    }
  };

  // 在组件顶部添加状态定义
  const [showFooterLink, setShowFooterLink] = useState(true);
  const [footerLinkText, setFooterLinkText] = useState('此服务由天工睿核公司提供');
  const [footerLinkUrl, setFooterLinkUrl] = useState('http://172.30.232.95:21080/register');

  const openIconList: ReactElement[] = [
    // <ThunderboltFilled {...commonIconProps} />,
    // <MessageFilled {...commonIconProps} />,
    // <CustomerServiceFilled {...commonIconProps} />,
    // <RobotFilled {...commonIconProps} />,
    // <CommentOutlined {...commonIconProps} />,
    // <SmileOutlined {...commonIconProps} />,
  ];

  const closeIconList: ReactElement[] = [
    // <CloseCircleFilled {...commonIconProps} />,
    // <CloseOutlined {...commonIconProps} />,
    // <DownCircleFilled {...commonIconProps} />,
    // <MinusCircleFilled {...commonIconProps} />,
  ];

  const handleCopy = async (text: string) => {
    try {
      // 检查是否支持现代 Clipboard API
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(text);
        message.success('复制成功');
      } else {
        // 降级到传统方法
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
          const successful = document.execCommand('copy');
          if (successful) {
            message.success('复制成功');
          } else {
            message.error('复制失败，请手动复制');
          }
        } catch (err) {
          message.error('复制失败，请手动复制');
        } finally {
          document.body.removeChild(textArea);
        }
      }
    } catch (error) {
      console.error('复制失败:', error);
      message.error('复制失败，请手动复制');
    }
  };

  const baseUrl = useMemo(() => {
    if (!shareLink) return '';
    const url = shareLink;
    return showHistory ? url : `${url}&showHistory=0`;
  }, [shareLink, showHistory]);

  const linkContent = baseUrl;
  const iframeContent = `<iframe
  src="${baseUrl}"
  style="width: 100%; height: 100%;"
  frameborder="0"
  allow="microphone"
/>`;
  const scriptContent = useMemo(() => {
    return `<script
  src="http://172.30.232.95:21080/js/monaco-editor.0.45.0/vs/iframe.js"
  id="chatbot-iframe" 
  data-bot-src="${baseUrl}" 
  data-default-open="${defaultOpen}"
  data-drag="${isDraggable}"
  data-open-icon="${openIcon}"
  data-close-icon="${closeIcon}"
  data-show-footer="${showFooterLink}"  
  data-footer-text="${footerLinkText}"  
  data-footer-url="${footerLinkUrl}"   
  defer
></script>
<script>
console.log("Chat box loaded")
</script>`;
  }, [
    baseUrl,
    defaultOpen,
    isDraggable,
    openIcon,
    closeIcon,
    showFooterLink,
    footerLinkText,
    footerLinkUrl,
  ]);

  const usageOptions = {
    link: {
      image: LinkImage,
      title: '将下面链接复制到浏览器打开',
      content: linkContent,
      options: <OptionItem label="展示历史对话" checked={showHistory} onChange={setShowHistory} />,
    },
    iframe: {
      image: IframeImage,
      title: '复制下面 iframe 加入到你的网站中',
      content: iframeContent,
      options: <OptionItem label="展示历史对话" checked={showHistory} onChange={setShowHistory} />,
    },
    script: {
      image: ScriptImage,
      title: '将下面代码加入到你的网站中',
      content: scriptContent,
      options: (
        <div className="grid grid-cols-3 gap-4">
          <OptionItem label="展示历史对话" checked={showHistory} onChange={setShowHistory} />
          <OptionItem label="图标可拖拽" checked={isDraggable} onChange={setIsDraggable} />
          <OptionItem label="默认打开" checked={defaultOpen} onChange={setDefaultOpen} />
          <OptionItem label="显示底部链接" checked={showFooterLink} onChange={setShowFooterLink} />
          <IconOptionItem
            label="打开图标"
            icon={openIcon}
            onIconChange={setOpenIcon}
            iconList={openIconList}
            onFileUpload={(file) => handleFileUpload(file, setOpenIcon)}
          />
          <IconOptionItem
            label="关闭图标"
            icon={closeIcon}
            onIconChange={setCloseIcon}
            iconList={closeIconList}
            onFileUpload={(file) => handleFileUpload(file, setCloseIcon)}
          />
        </div>
      ),
    },
  };

  const activeContent = usageOptions[activeUsage];

  return (
    <Modal title="选择使用方式" open={open} onCancel={onCancel} footer={null} width={700}>
      <div className="space-y-6">
        <div className="flex justify-center space-x-4">
          {Object.keys(usageOptions).map((key) => (
            <div
              key={key}
              className={`cursor-pointer rounded-lg border p-1 transition-all duration-200 ${
                activeUsage === key ? 'border-blue-500' : 'border-gray-200'
              }`}
              onClick={() => setActiveUsage(key as UsageType)}
            >
              <img src={usageOptions[key as UsageType].image} alt={key} className="h-28" />
            </div>
          ))}
        </div>

        <div>{activeContent.options}</div>

        <div>
          <div className="mb-2 flex items-center justify-between">
            <span className="font-medium text-gray-700">{activeContent.title}</span>
            <Button icon={<CopyOutlined />} onClick={() => handleCopy(activeContent.content)} />
          </div>
          <Input.TextArea
            value={activeContent.content}
            autoSize={{ minRows: 8, maxRows: 15 }}
            readOnly
            className="bg-gray-100 font-mono text-sm"
          />
        </div>
      </div>
    </Modal>
  );
};

export default UsageMethodModal;
